package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.admin.entity.AdChannel;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.service.AdChannelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.PageRequestDto;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.admin.dtos.ChannelDto;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 频道信息表 服务实现类
 * </p>
 *
 * @author RMY
 * @since 2021-11-22
 */
@Service
public class AdChannelServiceImpl extends ServiceImpl<AdChannelMapper, AdChannel> implements AdChannelService {

    //分页查询频道列表
    @Override
    public PageResult<ChannelDto> findByPage(ChannelDto channelDto) {
        //1.初始化分页
        Page<AdChannel> page = new Page<>(channelDto.getPage(), channelDto.getSize());
        //2.构造查询条件
        QueryWrapper<AdChannel> qw = new QueryWrapper<>();
        //3.判断参数
        if (StringUtils.isNotBlank(channelDto.getName())){
            //不为空则查询
            qw.lambda().like(AdChannel::getName,channelDto.getName());
        }
        //4.分页查询
        IPage<AdChannel> iPage = this.page(page, qw);
        //5.判断结果是否为空
        if (CollectionUtils.isEmpty(iPage.getRecords())){
            //5.1为空则返回空
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //5.2不为空就返回最终结果
        List<ChannelDto> channelDtoList = BeanHelper.copyWithCollection(iPage.getRecords(), ChannelDto.class);
        //封装dto,并返回
        return new PageResult<>(channelDto.getPage(),channelDto.getSize(),iPage.getTotal(),channelDtoList);
    }


}
